package com.ruoyi.dm.component;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ArrayUtil;
import com.alibaba.fastjson.JSON;
import com.ruoyi.common.constant.CollectFileTypeConstants;
import com.ruoyi.common.utils.biz.BizModule;
import com.ruoyi.common.utils.biz.PathUtil;
import com.ruoyi.dm.component.manager.DensityDataManager;
import com.ruoyi.dm.domain.po.AirCollectRecordPO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.input.ReversedLinesFileReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.util.LinkedHashMap;

/**
 * 空间 密度数据策略
 */
@Component
@Slf4j
public class DenstiyDataStrategy implements DataStrategy<AirCollectRecordPO> {

    @Autowired
    private DensityDataManager densityDataManager;

    @Override
    public AirCollectRecordPO makeupPo(AirCollectRecordPO po) {

        String fullPath = PathUtil.outputModuleDir(BizModule.COLLECT)+po.getFilePath();
        File path = new File(fullPath, po.getFileName());
        ReversedLinesFileReader reader = null;
        try {
            reader = ReversedLinesFileReader.builder().setFile(path).get();
            String line = "";
            while (null != (line=reader.readLine())) {
                // 截取最新数据时间
                // 1964-04-09 00:00:00
                if (StringUtils.hasLength(line)) {
                    String str =  line.substring(0,10);
                    TemporalAccessor parse = DateTimeFormatter.ofPattern("yyyy-MM-dd").parse(str);
                    po.setFileDate(LocalDate.from(parse));
                    break;
                }
            }
        } catch (Exception e) {
            log.error("解析时间异常",e);
        }finally {
            if (null != reader) {
                try {
                    reader.close();
                } catch (IOException e) {
                    //ignore
                }
            }
        }
        return po;
    }


    @Override
    public String pythonCmd(String satellite, String dataType, String filePath, String method, Integer year) {
        String fileType = CollectFileTypeConstants.TYPE_DEN;
        String outPath = PathUtil.outputModuleDir(BizModule.COLLECT) + PathUtil.moduleDirs().getCollect().get("result") + "/" + fileType;
        FileUtil.mkdir(outPath);
        String logPath = PathUtil.tmpModuleDir(BizModule.COLLECT) + PathUtil.moduleDirs().getCollect().get("result") + "/" + fileType;
        FileUtil.mkdir(logPath);
        String script = PathUtil.codeModuleDir(BizModule.COLLECT) + PathUtil.moduleDirs().getCollect().get("densityScript");
        String tmpPath = PathUtil.tmpModuleDir(BizModule.COLLECT) + PathUtil.moduleDirs().getCollect().get("result");
        File inputFile = new File(tmpPath, new File(filePath).getName() + ".json");
        //将参数写入文件
        LinkedHashMap<String, Object> object = new LinkedHashMap<>();
        //必需按这个顺序
        object.put("FILE_PATH", filePath);
        object.put("RESULT_PATH", outPath);
        //这些参数是固定的
        object.put("threshold_density", 2.3);
        object.put("threshold_altitude", 1.2);
        String param = JSON.toJSONString(object);
        FileUtil.writeString(param, inputFile, StandardCharsets.UTF_8);
        String[] cmdLines = new String[3];
        cmdLines[0] = "python";
        cmdLines[1] = script;
        cmdLines[2] = inputFile.getAbsolutePath();
        String commond = ArrayUtil.join(cmdLines, " ");
        log.info("拼接脚本:{},{}", commond, param);
        return commond;
    }


    @Override
    public void save(String satellite, String outFile) throws Exception {
        densityDataManager.saveDensityData(satellite,outFile);
    }
}
